package com.example.a2209_mianshi.ui.mall.view

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModel
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.a2209_mianshi.R
import com.example.a2209_mianshi.base.BaseActivity
import com.example.a2209_mianshi.base.BaseMallHomeDataFragment
import com.example.a2209_mianshi.base.state.RequestEvent
import com.example.a2209_mianshi.databinding.ActivityMallBinding
import com.example.a2209_mianshi.ui.mall.MallHomeMultiAdapter
import com.example.a2209_mianshi.ui.mall.model.MallBanner
import com.example.a2209_mianshi.ui.mall.model.MallGoods
import com.example.a2209_mianshi.ui.mall.model.MallHomeRowItem
import com.example.a2209_mianshi.ui.mall.model.MallRowTypes
import com.example.a2209_mianshi.ui.mall.viewModel.MallViewModel
import dagger.hilt.android.AndroidEntryPoint
const val TAG = "MallActivity"
@AndroidEntryPoint
class MallActivity : BaseMallHomeDataFragment<MallViewModel, ActivityMallBinding>() {
    private val viewModel : MallViewModel by viewModels()
    override val mLayoutResId: Int
        get() = R.layout.activity_mall

    override fun initData() {
        viewModel.cmallAdInfo()
        viewModel.cmallBannerInfo()
    }

    override fun initListener() {
        //状态管理
        addCommonStateListener(viewModel.mallMallGroupStateFlow)
        viewModel.mallAdInfoLiveData.observe(this){
            invalidateList(makeMallHomeForModel(viewModel))
        }
        addCommonStateListener(viewModel.bannerMallInfoStateFlow)
        viewModel.bannerMallInfoLiveData.observe(this){
            invalidateList(makeMallHomeList(viewModel))
        }
    }
    private val mHandler by lazy {
        Handler(Looper.getMainLooper())
    }
    override fun invalidateList(resultList: List<MallHomeRowItem>) {
        mBinding.rvMallHome.itemAnimator = null
        mHandler.removeCallbacksAndMessages(null)
        mHandler.postDelayed({
//            if (this != null) {
                setLoadingViewVisible(false)
                super.invalidateList(resultList)
//            }
        }, 666)
    }
    override fun initAdapter() {
        mAdapter = MallHomeMultiAdapter(mItems)
        // 动态设置spanCount
        val spanCount = 2
        val layoutManager: GridLayoutManager = mBinding.rvMallHome.layoutManager as GridLayoutManager
        layoutManager.spanCount = spanCount
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return try {
                    if (mItems.isEmpty())
                        return 0
                    mItems[position].getSpanSize()
                } catch (e: Exception) {
                    0
                }
            }
        }
        mBinding.rvMallHome.layoutManager = layoutManager
        bindAdapter(mBinding.rvMallHome)
    }
    fun makeMallHomeList(vm: MallViewModel? = null): List<MallHomeRowItem> {
        val list = ArrayList<MallHomeRowItem>()
        vm?.mallBannersLiveData?.value?.apply {
//            this.forEach { it.adAddr = "skl_app_home_banner" }
            // list.add(MallHomeRowItem(type = MallRowTypes.BANNER, banners = mockBanners()))
            if (this.isNotEmpty()) {
                list.add(MallHomeRowItem(type = MallRowTypes.BANNER, banners = this))
            }
        }
        /**添加跳蚤市场，二手车等第三方服务，在第二个item*/
        list.add(MallHomeRowItem(type = MallRowTypes.THIRD_SERVICE))
        return list
    }
    fun makeMallHomeForModel(vm: MallViewModel? = null): List<MallHomeRowItem> {
        val list = ArrayList<MallHomeRowItem>()
        // Banner
        vm?.commGoodsInfo?.value?.apply {
//            val banners = if (!this.posterUll.isNullOrEmpty()) {
//                this.posterUll.map {
//                    MallBanner(
//                        id = 0L, imageUrl = it, video = "", url = "", dataId = this.id, type = "in",
//                        modelCode = this.modelCode, modeName = this.modelName, productType = this.productType
//                    )
//                }
//            } else {// 接口返回的商品没有轮播图，加一个假的图片地址，这样就会展示占位图了
//                listOf(
//                    MallBanner(
//                        id = 0L, imageUrl = "empty_img", video = "", url = "", dataId = this.id, type = "in",
//                        modelCode = this.modelCode, modeName = this.modelName, productType = this.productType
//                    )
//                )
//            }
            //使用主图
            val banners = if (!this.mallGoodsInfoPageResponseList[0].mainImgUrl.isNullOrEmpty()) {
                listOf(
                    MallBanner(
                        id = 0L, imageUrl = this.mallGoodsInfoPageResponseList[0].mainImgUrl!!, url = "", dataId = this.id, type = "in",
//                        modelCode = this.modelCode, modeName = this.modelName, productType = this.productType
                    )
                )
            } else {// 接口返回的商品没有轮播图，加一个假的图片地址，这样就会展示占位图了
                listOf(
                    MallBanner(
                        id = 0L, imageUrl = "empty_img", url = "", dataId = this.id, type = "in",
//                        modelCode = this.modelCode, modeName = this.modelName, productType = this.productType
                    )
                )
            }
            list.add(MallHomeRowItem(type = MallRowTypes.BANNER, banners = banners))
        }
        // 为你推荐
//        vm?.recommendGoodsList?.value?.apply {
//            if (this.isNotEmpty()) {// 推荐列表不为空时才展示
//                list.add(MallHomeRowItem(type = MallRowTypes.TITLE, title = "为你推荐", id = longId(), tag = MallRowTags.GOODS_RECOMMEND))
//                // list.add(MallHomeRowItem(type = MallRowTypes.RECOMMEND, goodsList = mockGoodsListByCount(8)))
//                list.add(MallHomeRowItem(type = MallRowTypes.RECOMMEND, goodsList = this))
//            }
//        }
//        list.add(MallHomeRowItem(type = MallRowTypes.TITLE, title = "周边文创", id = longId(), tag = MallRowTags.GOODS))
//        for (i in 1..4) {
//            list.add(MallHomeRowItem(type = MallRowTypes.GOODS, goods = mockSingleGoods()))
//        }
        return list
    }
}